#region license
# This file is part of Grawlix.
# 
# Grawlix is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
# 
# Grawlix is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public
# License along with Grawlix.  If not, see
# <http://www.gnu.org/licenses/>.
#endregion

"""An interface representing an immutable loadable resource."""

namespace Grawlix.Services.Resources
import System
import System.Runtime.Serialization
import System.Security.Permissions

abstract class AbstractResourceProxy[of
	T/*(interface, IDynamicResource)*/](
	/*T,*/
	ISerializable):
"""Base class for resource proxies, containing the real functionality."""
	
	protected def constructor([required] identifier as Uri):
	"""
	Initializes the resource with a given URI.
	Param identifier: The unique identifier of this resource.
	"""
		_identifier = identifier
	
	[SecurityPermission(
		SecurityAction.LinkDemand,
		Flags: SecurityPermissionFlag.SerializationFormatter)]
	def GetObjectData(
		[required] info as SerializationInfo,
	    context as StreamingContext):
	"""
	Get serialization info that can be used across AppDomains.
	Param info: The Serialization info available.
	Param context: The StreamingContext of the serialization.
	"""
		if _resourceCache is null:
			raise SerializationException(
				"Attempt to serialize a detached resource proxy.")
		info.AddValue("Identifier", Identifier, Uri)
		info.AddValue(
			"Repository",
			_resourceCache.Repository,
			ResourceRepository[of T])
		info.SetType(typeof(ResourceObjectReference[of T]))
	
	def destructor():
	"""Notifies the cache that the proxy has died."""
		unless _resourceCache is null:
			_resourceCache.RemoveResource(
				# FIXME: Cast needed for bug in Boo generics
				self as AbstractResourceProxy[of T])
	
	# FIXME: Boo bug requires this be not internal
	/*internal */def Attach(resourceCache as ResourceCache[of T]):
	"""
	Attaches to the specified cache.
	Param resourceCache: The cache to attach to.
	"""
		_resourceCache = resourceCache
	
	# FIXME: Boo bug requires this be not internal
	/*internal */def SetState(resourceState as ResourceState):
	"""
	Sets the state of this resource.
	Param resourceState: The state information.
	"""
		_state = resourceState.StateObject
		_loadFailed = resourceState.LoadFailed
	
	protected def GetState() as object:
	"""
	Accesses the internal state information.
	Raises InvalidOperationException: If Ready is false.
	"""
		EnsureReady()
		return _state
	
	protected def EnsureReady():
	"""
	Convenience function that raises
	an <InvalidOperationException> if not ready.
	Raises InvalidOperationException: If Ready is false.
	"""
		if not Ready:
			raise InvalidOperationException(
				"Unable to access a resource (${self}) because " +
				"it is not yet ready. " +
				"Be sure to check the Ready parameter before " +
				"accessing most resource operations.")
	
	override def ToString():
	"""
	Get a string representation of this resource.
	Returns: The string representation.
	"""
		return "${typeof(T).Name} ${Identifier}"
	
	# HACK: Workaround; do not change implementation.
	virtual Ready as bool:
	"""
	Whether or not the resource is ready to use.
	Remarks: It will never become true if the resource fails
		to load.
	"""
		get:
			return _state is not null
	
	virtual LoadFailed as bool:
	"""Whether or not the resource load failed."""
		get:
			return _loadFailed
	
	virtual Identifier as Uri:
	"""Whether or not the resource load failed."""
		get:
			return _identifier
	
	private _state
	"""The internal state data."""
	
	private _loadFailed as bool
	"""Whether or not the resource load failed."""
	
	private _identifier as Uri
	"""The URI that this resource was created with."""
	
	private _resourceCache as ResourceCache[of T]
	"""The resource cache that owns this proxy."""
	
